<?php

namespace app\shop\controller\order;

use cat;
use think\Controller;

/**
 * 订单控制器
 */
class Order extends Controller
{
    public function __construct()
    {
        // 继承父类
        parent::__construct();

        $this->ProductModel = model('Product.Product');
        $this->OrderProductModel = model('Order.Product');
        $this->OrderModel = model('Order.Order');
        $this->CartModel = model('Order.Cart');
        $this->BusinessModel = model('Business.Business');
        $this->AddressModel = model('Business.Address');

        // 获取系统配置里面的选项
        $this->url = config('site.url') ? config('site.url') : '';

        // 判断用户是否存在
        if ($this->request->isAjax()) {
            // 接收用户id
            $this->busid = $this->request->param('busid', 0, 'trim');

            $business = $this->BusinessModel->find($this->busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }
        }
    }

    // 下订单
    public function add()
    {
        if ($this->request->isAjax()) 
        {
            $addrid = $this->request->param('addrid', 0, 'trim');
            $cartids = $this->request->param('cartids', 0, 'trim');
            $remark = $this->request->param('remark', 0, 'trim');

            // 查询出用户信息
            $business = $this->BusinessModel->find($this->busid);

            if($business['status'] == 0)
            {
                $this->error('您的账号，暂未通过邮箱认证，请认证后下单');
                exit;
            }

            // 判断收货地址是否存在
            $where = [
                'busid' => $this->busid,
                'id' => $addrid
            ];

            $address = $this->AddressModel->where($where)->find();

            if(!$address)
            {
                $this->error('收货地址不存在');
                exit;
            }

            $where = [
                'cart.id' => ['in', $cartids]
            ];

            // 购物车列表
            $cartlist = $this->CartModel->with(['product'])->where($where)->select();

            // 统计要下单购物车的总计
            $total = $this->CartModel->with(['product'])->where($where)->sum('total');

            if(!$cartlist)
            {
                $this->error('购物车记录为空');
                exit;
            }

            // 判断库存够不够
            foreach($cartlist as $cart)
            {
                // 库存树 < 购物数量
                if($cart['product']['stock'] < $cart['pronum'])
                {
                    $this->error($cart['product']['name']."库存不足，无法下单");
                    exit;
                }
            }

            // 判断钱够不够
            $UpdateMoney = bcsub($business['money'], $total);

            if($UpdateMoney < 0)
            {
                $this->error('余额不足请先充值');
                exit;
            }

            // 订单表 插入
            // 订单商品表 插入
            // 商品表 更新
            // 用户表 更新
            // 用户的消费记录表 插入
            // 购物车 删除

            $OrderModel = model('Order.Order');
            $OrderProductModel = model('Order.Product');
            $ProductModel = model('Product.Product');
            $RecordModel = model('Business.Record');
            $BusinessModel = model('Business.Business');
            $CartModel = model('Order.Cart');

            // 开启事务
            $OrderModel->startTrans();
            $OrderProductModel->startTrans();
            $ProductModel->startTrans();
            $RecordModel->startTrans();
            $BusinessModel->startTrans();
            $CartModel->startTrans();

            // 生成订单编号
            $code = build_code('FA');

            // 组装数据
            $OrderData = [
                'code' => $code,
                'busid' => $business['id'],
                'businessaddrid' => $addrid,
                'amount' => $total,
                'remark' => $remark,
                'status' => 1,
                'adminid' => $business['adminid'],
            ];

            // 插入订单数据
            $OrderStatus = $OrderModel->validate('common/Order/Order')->save($OrderData);

            if($OrderStatus === FALSE)
            {
                $this->error($OrderModel->getError());
                exit;
            }

            // 整理订单商品数据
            $OrderProductData = [];

            // 整理商品表更新库存的数据
            $ProductData = [];
            foreach($cartlist as $item)
            {
                // 插入
                $OrderProductData[] = [
                    'orderid' => $OrderModel->id,// 获取上一步插入的自增id
                    'proid'=>$item['proid'],
                    'pronum'=>$item['pronum'],
                    'price'=>$item['price'],
                    'total'=>$item['total'],
                ];

                // 更新 商品库存 - 购买数量
                $UpdateStock = bcsub($item['product']['stock'], $item['pronum']);

                $ProductData[] = [
                    'id' => $item['proid'],
                    'stock' => $UpdateStock
                ];
            }

            // 多条插入
            $OrderProductStatus = $OrderProductModel->validate('common/Order/Product')->saveAll($OrderProductData);

            if($OrderProductStatus === FALSE)
            {
                $OrderModel->rollback();
                $this->error($OrderProductModel->getError());
                exit;
            }

            // 执行更新商品表库存语句
            $ProductStatus = $ProductModel->isUpdate(true)->saveAll($ProductData);

            if($ProductStatus === FALSE)
            {
                $OrderProductModel->rollback();
                $OrderModel->rollback();
                $this->error($ProductModel->getError());
                exit;
            }

            // 更新用户的余额
            $BusinessData = [
                'id'=>$business['id'],
                'money'=>$UpdateMoney
            ];

            $BusinessStatus = $BusinessModel->isUpdate(true)->save($BusinessData);

            if($BusinessStatus === FALSE)
            {
                $ProductModel->rollback();
                $OrderProductModel->rollback();
                $OrderModel->rollback();
                $this->error($BusinessModel->getError());
                exit;
            }

            // 用户消费记录表 插入
            $RecordData = [
                'total' => "-$total",
                'content' => "购买商品，订单号：【{$code}】",
                'busid' => $business['id']
            ];

            $RecordStatus = $RecordModel->validate('common/Business/Record')->save($RecordData);

            if($RecordStatus === FALSE)
            {
                $BusinessModel->rollback();
                $ProductModel->rollback();
                $OrderProductModel->rollback();
                $OrderModel->rollback();
                $this->error($BusinessModel->getError());
                exit;
            }

            // 删除购物车记录
            $where = ['id' => ['in', $cartids]];

            $CartStatus = $CartModel->where($where)->delete();

            if($CartStatus === FALSE)
            {
                $RecordModel->rollback();
                $BusinessModel->rollback();
                $ProductModel->rollback();
                $OrderProductModel->rollback();
                $OrderModel->rollback();
                $this->error($BusinessModel->getError());
                exit;
            }

            if($OrderStatus === FALSE || $OrderProductStatus === FALSE || $ProductStatus === FALSE || $BusinessStatus === FALSE || $RecordStatus === FALSE || $CartStatus === FALSE)
            {
                $CartModel->rollback();
                $RecordModel->rollback();
                $BusinessModel->rollback();
                $ProductModel->rollback();
                $OrderProductModel->rollback();
                $OrderModel->rollback();
                $this->error('下单失败');
                exit;
            }else
            {
                $OrderModel->commit();
                $OrderProductModel->commit();
                $ProductModel->commit();
                $BusinessModel->commit();
                $RecordModel->commit();
                $CartModel->commit();
                $this->success('下单成功，等待商家发货', '/order/order/index');
                exit;
            }
        }
    }

    // 订单列表
    public function index()
    {
        if($this->request->isAjax())
        {
            $busid = $this->request->param('busid', 0, 'trim');
            $status = $this->request->param('status', 0, 'trim');

            // 组装条件
            $where = [
                'busid' => $busid,
            ];

            if($status)
            {
                $where['status'] = $status;
            }

            $list = $this->OrderModel->where($where)->select();

            if($list)
            {
                foreach($list as &$item)
                {
                    // 查询该订单下面的订单商品
                    $item['prolist'] = $this->OrderProductModel->with(['proinfo'])->where(['orderid' => $item['id']])->find();
                }
            }

            $this->success('订单列表', null, $list);
            exit;
        }
    }

    // 订单详情
    public function info()
    {
        if($this->request->isPost())
        {
            $busid = $this->request->param('busid', 0, 'trim');
            $orderid = $this->request->param('orderid', 0, 'trim');

            $orderinfo = $this->OrderModel->find($orderid);

            if(!$orderinfo)
            {
                $this->error('订单不存在');
                exit;
            }

            // 订单商品
            $product = $this->OrderProductModel->with(['proinfo'])->where(['orderid' => $orderid])->select();

            // 判断订单商品是否存在
            if(!$product)
            {
                $this->error('订单商品不存在');
                exit;
            }

            // 获取订单的收货地址
            $address = $this->AddressModel->with(['provinces', 'citys', 'districts'])->find($orderinfo['businessaddrid']);

            if(!$address)
            {
                $this->error('未找到订单的收货地址');
                exit;
            }

            $data = [
                'order' => $orderinfo,
                'product' => $product,
                'address' => $address
            ];

            $this->success('返回订单数据成功', null, $data);
            exit;
        }
    }

    public function express()
    {
        if($this->request->isAjax())
        {
            $orderid = $this->request->param('orderid', 0, 'trim');

            //判断订单是否存在
            $order = $this->OrderModel->with(['express'])->find($orderid);

            if(!$order)
            {
                $this->error('订单不存在');
                exit;
            }

            if(empty($order['expresscode']))
            {
                $this->error('暂无物流单号');
                exit;
            }

            if(empty($order['express']['name']))
            {
                $this->error('物流公司未知');
                exit;
            }

            //先判断缓存中是否有查询过的记录，如果有就不去在调用接口了
            $cache = cache($order['expresscode']);
            if($cache)
            {
                if($cache)
                {
                    //返回缓存数据
                    $this->success('返回物流信息', null, $cache);
                    exit;
                }else
                {
                    $this->error('暂无物流信息');
                    exit;
                }
            }else
            {
                $success = query_express($order['expresscode']);

                if($success['result'])
                {
                    //存放缓存信息
                    cache($order['expresscode'], $success['data']);
                    $this->success('返回物流信息', null, $success['data']);
                    exit;
                }else
                {
                    //存放缓存信息
                    cache($order['expresscode'], []);
                    $this->error($success['msg']);
                    exit;
                }
            }
        }
    }
}
